var express = require('express')
var router = express.Router()
var db = require('../db/index')

router.get('/', (req, res) => {
    let userInfo = req.session.userInfo
    db.userList(function (err, result) {
        let data = []
        if (result) {
            console.log(result)
            data = result
        }
        res.render('users', { data, userInfo })
    })
})

router.get('/add', (req, res) => {
    let action = '/users/add'
    res.render('userAU', { action })
})

router.post('/add', (req, res) => {
    db.addUser(req.body, function (err, result) {
        let msg
        msg = err ? '添加用户失败！！' : '添加用户成功！！'
        let userInfo = req.session.userInfo
        res.render('msg', { msg, userInfo })
    })
})

router.get('/update/:id', (req, res) => {
    db.getUserById(req.params.id, function (err, result) {
        if (err) {
            res.render(msg, err.message)
        }
        if (result) {
            console.log(result)
            let data = {
                action: '/users/update/' + req.params.id,
                ...result[0]
            }
            console.log(data)
            res.render('userAU', data)
        }

    })
})


router.post('/update/:id', (req, res) => {
    db.updateUser(req.body, req.params.id, function (err, result) {
        let msg
        msg = err ? '修改用户失败！！' : '修改用户成功！！'
        let userInfo = req.session.userInfo
        res.render('msg', { msg, userInfo })
    })
})



router.get('/del/:id', (req, res) => {
    let id = req.params.id
    console.log(id)
    db.delUser(id, function (err, result) {
        if (err) {
            let userInfo = req.session.userInfo
            res.render('msg', { msg: '刪除失败！', userInfo })
        } else {
            res.redirect('/users')
        }
    })

})
module.exports = router